package com.spi.controller;

import com.spi.config.MyWebSocketHandler;
import com.spi.sentinel.RateLimiter;
import com.spi.service.AsyncService;
import com.spi.xxjob.ScheduleJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("/survey/01")
@RestController
@Slf4j
public class TestController {

    @Autowired
    private AsyncService asyncService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate ;

    /**
     * websocket整体流程：
     * 前端用户点击按钮，触发 WebSocket 连接建立,后端返回代表当前websocket的唯一标识，并存储在自身节点的静态常量中。
     * 前端带着唯一标识发送 HTTP 请求给后端，后端将信息扔进mq中并直接返回。
     * mq消费者端进行加锁、多线程、汇总结果及落库、释放锁等动作。
     * 任务执行完毕后消费者端会将websocket唯一标识扔进mq中，mq消费者端采用集群模式进行消费。
     * mq消费者端集群模式去看自身节点是否存在该websocket唯一标识，若不存在直接return，存在则进行通知前端，将消息显示在页面上。
     * @param sockId
     * @return
     */
    @GetMapping("/startTask/{sockId}/{contendId}")
    @CrossOrigin("http://localhost:63342")
    public String startTask(@PathVariable String sockId,@PathVariable String contendId) {
        System.out.println("进入后台接口。。。");
        log.info("进入后台接口。。。");
        //mq发送消息
        System.out.println("准备mq发送消息。。。");
        log.info("准备mq发送消息。。。");
        String prodKey = UUID.randomUUID().toString();
        Map<String,String> map = new HashMap<>() ;
        map.put("prodKey",prodKey);
        map.put("sockId",sockId);
        map.put("contendId",contendId);
        Message<Map<String, String>> mapMessage = MessageBuilder.withPayload(map).build();
        rocketMQTemplate.asyncSend("survey-topic-autoBuildConclusion", mapMessage, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("survey-topic-autoBuildConclusion消息投递成功==mq生成消息id为"+sendResult.getMsgId());
                log.info("survey-topic-autoBuildConclusion消息投递成功==mq生成消息id为"+sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("survey-topic-autoBuildConclusion消息投递失败。。。");
                log.info("survey-topic-autoBuildConclusion消息投递失败。。。");
            }
        });
        //asyncService.doLongTask(sockId);
        return "任务已开始处理，请等待通知";
    }

    @CrossOrigin("http://localhost:63342")
    @GetMapping("/removeSessionData/{socketid}")
    public String removeSessionData(@PathVariable String socketid) {
        boolean b = asyncService.removeSessionData(socketid);
        if (b){
            return "移除容器内元素" ;
        }else {
            return "未移除容器内元素" ;
        }
    }

    @RateLimiter(
            key = "sentinel:01",
            permitsPerSecond = 2,
            timeout = 0,
            timeUnit = TimeUnit.MILLISECONDS,
            message = "服务器繁忙请等待")
    @RequestMapping("/test02")
    public void test02(){
        System.out.println("进来了。。。");
    }



























}
